package com.itstyle.mytest.threadpoolexecutor;

import com.itstyle.mytest.threadpoolexecutor.exception.PolicyException;
import com.itstyle.mytest.threadpoolexecutor.policy.PolicyHandler;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xianguang
 * @date 2020-01-06 13:59
 */
public class ThreadPoolExecutor implements ExecutorService {

    //记录当前alive的线程数
    private AtomicInteger act=new AtomicInteger();

    //拒绝策略
    private volatile PolicyHandler handler;

    //核心线程数
    private int poolSize;

    //阻塞队列，保存任务
    private BlockingQueue<Runnable> workQueue;

    private volatile boolean allowThreadTimeOut=false;

    private final long keepAliveTime;

    private ReentrantLock mainLock=new ReentrantLock();

    private volatile boolean isShutDown=false;

    private volatile long completeTaskCount=0;

    public ThreadPoolExecutor(int poolSize,int queueSize, long keepAliveTime,PolicyHandler handler) {
        if(poolSize<=0)
            throw new PolicyException("核心线程数不为空");
        this.handler = handler;
        this.poolSize = poolSize;
        this.keepAliveTime = keepAliveTime;
        if(keepAliveTime>0)
            allowThreadTimeOut=true;
        this.workQueue=new ArrayBlockingQueue<>(5);
    }

    /**
     * 提交任务
     * @param task
     */
    @Override
    public void execute(Runnable task) {

    }

    /**
     * 关闭线程池
     */
    @Override
    public void shutdown() {

    }

    public Runnable getTask(){
        return this.workQueue.poll();
    }

    /**
     * 核心干活的工人
     */
    class Worker implements Runnable {
        final Thread thread;
        Runnable firstTask;

        public Worker(Runnable task) {
            this.firstTask = task;
            this.thread = new Thread(this);
        }


        @Override
        public void run() {
            while(firstTask!=null||getTask()!=null){

            }
        }
    }
}
